"use strict";
/**
 * @name login
 * 用户登录
 */

/**
 * @name /
 * @param string access 认证信息
 * @return string session id
 * 账号登录
 *
 */


module.exports = function () {
    let access = this.get('access');
    let guid = this.get('guid');
    
    //使用GUID登录
    if (guid) {
        this.uid = guid;
        this.updater.role.key("guid");
        return Promise.resolve().then(() => {
            return this.updater.data();
        }).catch(err => {
            // 如果用户不存在，创建新账号
            if (err.ret === 'hwc' && err.err === 'user_not_exist') {
                let name = `Player_${guid.slice(-6)}`;
                // 设置session中的guid
                this.session.guid = guid;
                this.req.body = { name: name };
                
                // 直接用create.js中的逻辑
                let role = this.model.mongo('role', this.sid);
                let usrData = { "sid": this.sid, "guid": guid, "name": name };
                
                return Promise.resolve().then(() => {
                    return this.library('guid/uid', this.sid);
                }).then(uid => {
                    let time = Date.now();
                    this.uid = uid;
                    usrData['_id'] = uid;
                    usrData['time'] = time;
                    usrData['login'] = 0;
                    usrData['lv'] = 1;
                    
                    return role.insert(usrData);
                }).then(() => {
                    // 重新设置uid和guid
                    this.uid = usrData['_id'];
                    this.updater.role.key("guid");
                    return this.updater.data();
                }).then(() => {
                    let INFO = {};
                    INFO['guid'] = guid;  // 使用原始的guid
                    INFO['isDev'] = 1;
                    return create_login_session.call(this, INFO);
                });
            }
            throw err;
        });
    }

    // 否则走正常的access登录流程
    if (!access) {
        return this.error('access empty');
    }

    // if(this.sid==996){
    //     return this.error('you can not login 996');
    // }
    // console.log("login first   access:%s",access);
    return Promise.resolve().then(() => {
        let api = '/access/';
        let data = { "sid": this.sid, "access": access };
        // console.log("login first   sid:%s",this.sid);
        return this.library('spirit/gzone', api, data)
    }).then(ret => {
        return create_login_session.call(this, ret);
    })
    // .then(ret => {
    //     for (let key in ret) {
    //         //验证是否输入过身份证号码
    //         if (ret[key]['idcard'] == '') {
    //             return this.error('idcard empty');
    //         } else {
    //             //验证是否是未成年
    //             return ret;
    //         }
    //     }
    //     // return ret;
    // })
}


// /**
//  * @name debug
//  * @param string uid 角色uid
//  * UID登录,必须DEBUG状态下可用
//  */
// module.exports.debug = function () {
//     let uid = this.get('uid','string');
//     if ( !uid ) {
//         return this.error('uid empty');
//     }
//     this.uid = uid;
//     this.updater.role.key("guid");
//     return Promise.resolve().then(()=>{
//         return this.updater.data()
//     }).then(()=>{
//         let INFO = {};
//         INFO['guid'] = this.updater.role.get("guid");
//         return create_login_session.call(this,INFO);
//     })
// }



/**
 * @name e996
 * @param string uid 角色uid
 * uid登录996服务器
 */
module.exports.e996 = async function () {
    let uid = this.get('uid', 'string');
    if (!uid) {
        return this.error('uid empty');
    }
    let user = this.get("user");
    if (!user) {
        return this.error("user empty");
    }
    let pass = this.get("pass");
    if (!pass) {
        return this.error("pass empty");
    }
    if (this.sid != 996) {
        return this.error('it is not 996 server');
    }
    let api = '/develop996/';
    let _ret = await this.library('spirit/gzone', api, this.req.body);
    if (!_ret) { return this.error('auth fail') };
    this.uid = uid;
    this.updater.role.key("guid");
    await this.updater.data();
    let INFO = {};
    INFO['guid'] = this.updater.role.get("guid");
    return create_login_session.call(this, INFO);
}

function create_login_session(INFO) {
    return Promise.resolve().then(() => {
        if (!INFO || !INFO['guid']) {
            return this.error('guid empty:' + JSON.stringify(INFO));
        }
        let loginVerify = this.config.get("login.verify");
        if (typeof loginVerify === 'function') {
            return loginVerify.call(this, INFO);
        }
    }).then(() => {
        let guid = INFO['guid'];
        let isDev = INFO['isDev'] || 0;
        let data = { "guid": guid, "sid": this.sid, "isDev": isDev };
        return this.session.create(guid, data);
    }).then(cookie => {
        this.cookie = cookie;
        let oid = this.session.uid;
        let keys = ['_id', 'name', 'lv', 'time', 'idCard'];
        let role = this.model.mongo('role', this.sid);
        return role.findFromGuid(oid, keys);
    }).then(rows => {
        for (let index in rows) {
            if (rows[index]['idCard'] == '') {
                rows[index]['idCard'] = 0;
            } else {
                rows[index]['idCard'] = 1;
            }
        }
        let data = { "roles": rows, "cookie": { "key": this.session.opts.key, "val": this.cookie } };
        let loginMessage = this.config.get('login.message');
        if (typeof loginMessage === 'function') {
            return loginMessage.call(this, data);
        }
        else if (loginMessage && typeof loginMessage === 'object') {
            return Object.assign(data, loginMessage);
        }
        else {
            return data;
        }
    })
}